<template>
  <view class="pet-my-container">
    <!-- 顶部背景 -->
    <view class="pet-header">
      <!-- <image
        class="header-pattern"
        src="/static/img/header-pattern.png"
        mode="scaleToFill"
      ></image> -->
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-avatar-area">
        <u-avatar
          class="avatar"
          bg-color="#fff"
          size="140"
          :src="userInfo.avatarUrl || '/static/img/default-pet-avatar.svg'"
        ></u-avatar>
        <view class="paw-icon paw-icon-1"></view>
        <view class="paw-icon paw-icon-2"></view>
        <view class="paw-icon paw-icon-3"></view>
        <view class="paw-icon paw-icon-4"></view>
      </view>
      <view class="user-info">
        <text class="username">{{
          userInfo.nickname || userInfo.realName || "铲屎官"
        }}</text>
        <text class="gender-info">{{
          userInfo.gender === 1
            ? "男生"
            : userInfo.gender === 2
            ? "女生"
            : "未设置性别"
        }}</text>
      </view>
      <view class="edit-profile-btn" @tap="openUpdateForm">
        <u-icon name="edit-pen" color="#8B5CFF" size="28"></u-icon>
        <text>编辑资料</text>
      </view>
    </view>

    <!-- 设置板块 -->
    <view class="settings-section">
      <view class="section-header">
        <view class="paw-mark"></view>
        <text>我的设置</text>
      </view>

      <view class="settings-list">
        <view
          class="settings-item"
          @tap="navigateTo('/pages/admin/petTemplate')"
        >
          <view class="item-left">
            <view class="icon-wrapper template-icon">
              <u-icon name="photo" color="#8B5CFF" size="40"></u-icon>
            </view>
            <text class="item-text">宠物形象管理</text>
          </view>
          <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view>
        <view
          class="settings-item"
          @tap="navigateTo('/pages/admin/systemConfig')"
        >
          <view class="item-left">
            <view class="icon-wrapper">
				<u-icon name="setting" color="#8B5CFF" size="40"></u-icon>
            </view>
            <text class="item-text">系统配置</text>
          </view>
          <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view>
        <view class="settings-item" @tap="navigateTo('/pages/my/about')">
          <view class="item-left">
            <view class="icon-wrapper">
              <u-icon name="info-circle" color="#8B5CFF" size="40"></u-icon>
            </view>
            <text class="item-text">关于我们</text>
          </view>
          <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-container">
      <button class="logout-button" @tap="logout">退出登录</button>
    </view>

    <!-- 底部装饰 -->
    <!-- <view class="footer-decoration">
      <view class="paw-steps"></view>
    </view> -->

    <!-- 用户资料修改弹窗 -->
    <view
      class="popup-mask"
      v-if="showUpdatePopup"
      @tap="closeUpdateForm"
    ></view>
    <view class="update-popup" v-if="showUpdatePopup">
      <view class="popup-header">
        <text class="popup-title">修改资料</text>
        <view class="close-btn" @tap="closeUpdateForm">
          <u-icon name="close" color="#999" size="24"></u-icon>
        </view>
      </view>

      <view class="popup-content">
        <!-- 头像上传 -->
        <view class="avatar-upload">
          <image
            class="current-avatar"
            :src="
              updateForm.avatarUrl ||
              userInfo.avatarUrl ||
              '/static/img/default-pet-avatar.svg'
            "
            mode="aspectFill"
          ></image>
          <view class="upload-btn" @tap="chooseAvatar">
            <u-icon name="camera-fill" color="#FFFFFF" size="24"></u-icon>
          </view>
        </view>

        <view class="form-item">
          <text class="form-label">昵称</text>
          <input
            class="form-input"
            v-model="updateForm.nickname"
            placeholder="请输入昵称"
          />
        </view>

        <view class="form-item">
          <text class="form-label">性别</text>
          <view class="gender-selector">
            <view
              class="gender-option"
              :class="{ selected: updateForm.gender === 1 }"
              @tap="selectGender(1)"
            >
              <text>男生</text>
            </view>
            <view
              class="gender-option"
              :class="{ selected: updateForm.gender === 2 }"
              @tap="selectGender(2)"
            >
              <text>女生</text>
            </view>
          </view>
        </view>

        <button class="submit-button" @tap="submitUpdateForm">保存修改</button>
      </view>
    </view>
  </view>
</template>

<script>
import global from "@/plugins/global";
export default {
  data() {
    return {
      global: global,
      userInfo: {},
      isAdmin: false,
      showUpdatePopup: false,
      updateForm: {
        nickname: "",
        gender: 0,
        avatarUrl: "",
      },
      genderArray: ["未知", "男", "女"],
      genderIndex: 0,
    };
  },
  onLoad() {
    this.userInfo = getApp().globalData;
    this.checkLoginStatus();
    this.checkAdminStatus();
  },
  onShow() {
    // 每次页面显示时都刷新用户信息
    this.fetchUserInfo();
  },
  methods: {
    // 通用页面跳转方法
    navigateTo(url) {
      uni.navigateTo({
        url: url,
      });
    },

    // 检查登录状态
    async checkLoginStatus() {
      try {
        const user = await this.$leanCloud.user.getCurrent();
        if (!user) {
          uni.redirectTo({
            url: "/pages/login/wechatEntry",
          });
        } else {
          this.userInfo = user;
          console.log("当前用户信息:", user);
        }
      } catch (error) {
        console.error("检查登录状态失败:", error);
      }
    },

    // 获取最新的用户信息
    async fetchUserInfo() {
      try {
        // 获取基本用户信息
        const user = await this.$leanCloud.user.getCurrent();
        if (user) {
          console.log("基本用户信息:", user);

          // 获取更完整的用户信息
          try {
            const userId = wx.getStorageSync("leancloud_user_id");
            if (userId) {
              // 通过用户ID获取用户详细信息
              const userDetail = await this.$leanCloud.get("_User", userId);
              console.log("获取到的用户详细信息:", userDetail);

              // 合并用户信息
              this.userInfo = {
                ...user,
                ...userDetail,
              };

              console.log("合并后的用户信息:", this.userInfo);
            } else {
              this.userInfo = user;
            }
          } catch (detailError) {
            console.error("获取用户详细信息失败:", detailError);
            // 如果获取详细信息失败，至少显示基本信息
            this.userInfo = user;
          }

          // 更新全局用户数据
          if (getApp() && getApp().globalData) {
            Object.assign(getApp().globalData, {
              nickname: this.userInfo.nickname,
              avatarUrl: this.userInfo.avatarUrl,
              isLogin: true,
            });
          }
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },

    // 检查管理员状态
    async checkAdminStatus() {
      try {
        const user = await this.$leanCloud.user.getCurrent();
        this.isAdmin = user && user.isAdmin;
      } catch (error) {
        console.error("检查管理员状态失败：", error);
      }
    },

    // 退出登录
    logout() {
      uni.showModal({
        title: "退出登录",
        content: "铲屎官确定要离开吗？",
        confirmColor: "#8B5CFF",
        success: async (res) => {
          if (res.confirm) {
            try {
              await this.$leanCloud.user.logout();
              wx.removeStorageSync("leancloud_session_token");
              wx.removeStorageSync("leancloud_user_id");
              if (getApp() && getApp().globalData) {
                getApp().globalData.isLogin = false;
                getApp().globalData.nickname = "";
                getApp().globalData.avatarUrl = "";
              }
              uni.reLaunch({
                url: "/pages/login/wechatEntry",
              });
            } catch (error) {
              console.error("退出登录失败:", error);
              uni.showToast({
                title: "退出失败，请重试",
                icon: "none",
              });
            }
          }
        },
      });
    },

    // 打开用户资料修改表单
    openUpdateForm() {
      // 初始化表单数据
      this.updateForm.nickname = this.userInfo.nickname || "";
      this.updateForm.gender = this.userInfo.gender || 0;
      this.updateForm.avatarUrl = this.userInfo.avatarUrl || "";

      // 显示弹窗
      this.showUpdatePopup = true;
    },

    // 关闭用户资料修改表单
    closeUpdateForm() {
      this.showUpdatePopup = false;
    },

    // 选择性别
    selectGender(gender) {
      this.updateForm.gender = gender;
    },
    async chooseAvatar() {
      try {
        // 使用Promise风格调用uni.chooseImage
        const chooseImagePromise = () => {
          return new Promise((resolve, reject) => {
            uni.chooseImage({
              count: 1,
              sizeType: ["compressed"],
              sourceType: ["album"],
              success: resolve,
              fail: reject,
            });
          });
        };

        const res = await chooseImagePromise();

        if (res && res.tempFilePaths && res.tempFilePaths.length > 0) {
          const tempFilePath = res.tempFilePaths[0];
          const fileName = `template_${Date.now()}.jpg`;

          uni.showLoading({
            title: "上传中...",
          });

          // 使用项目中定义的文件上传API
          const fileData = await this.$leanCloud.file.upload(
            tempFilePath,
            fileName
          );

          // 获取文件URL
          this.updateForm.avatarUrl = fileData.url;

          uni.hideLoading();
        }
      } catch (error) {
        console.error("上传头像失败：", error);
        uni.showToast({
          title: "上传失败",
          icon: "none",
        });
      }
    },

    // 提交用户资料修改
    async submitUpdateForm() {
      try {
        // 显示加载提示
        uni.showLoading({
          title: "保存中...",
        });

        // 构建更新数据
        const updateData = {
          nickname: this.updateForm.nickname,
          gender: this.updateForm.gender,
		  avatarUrl: this.updateForm.avatarUrl,
        };

        // 使用 updateUserInfo 方法更新用户信息
        await this.$leanCloud.user.updateUserInfo(updateData);

        // 更新本地显示的用户信息
        this.userInfo = {
          ...this.userInfo,
          ...updateData,
        };

        // 更新全局数据
        if (getApp() && getApp().globalData) {
          Object.assign(getApp().globalData, {
            nickname: updateData.nickname,
            gender: updateData.gender,
            avatarUrl: updateData.avatarUrl || this.userInfo.avatarUrl,
          });
        }

        // 关闭弹窗
        this.closeUpdateForm();

        // 显示成功提示
        uni.showToast({
          title: "资料更新成功",
          icon: "success",
        });
      } catch (error) {
        console.error("更新用户信息失败:", error);
        uni.showToast({
          title: error.message || "更新失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 上传用户头像到LeanCloud
    async uploadUserAvatar(filePath) {
      try {
        uni.showLoading({
          title: "上传中...",
        });

        const fileName = `avatar_${Date.now()}.jpg`;

        // 使用项目中定义的文件上传API
        const fileData = await this.$leanCloud.file.upload(filePath, fileName);

        // 获取文件URL
        console.log("头像上传成功:", fileData);
        return fileData;
      } catch (error) {
        console.error("上传头像失败:", error);
        throw error;
      } finally {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style lang="scss">
/* 整体配色方案:
	 * 主色: #8B5CFF (温和的紫色)
	 * 辅助色: #FFD687 (温暖的橙黄色)
	 * 背景色: #F5F6FA (淡淡的灰蓝色背景)
	 * 文本颜色: #333, #666, #999 三级
	 */
page {
  background-color: #f5f6fa;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica,
    Segoe UI, Arial, Roboto, "PingFang SC", "miui", "Hiragino Sans GB",
    "Microsoft Yahei", sans-serif;
}

.pet-my-container {
  min-height: 100vh;
  position: relative;
  padding-bottom: 120rpx;
}

/* 头部区域 */
.pet-header {
  height: 280rpx;
  background: linear-gradient(135deg, #8B5CFF 0%, #6C3FFF 100%);
  position: relative;
  overflow: hidden;
  padding-top: env(safe-area-inset-top);

  .header-pattern {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0.1;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 60rpx;
    background: #F5F6FA;
    border-radius: 50% 50% 0 0;
  }
}

/* 用户卡片 */
.user-card {
  margin: -120rpx 30rpx 30rpx;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 30rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(139, 92, 255, 0.15);
  position: relative;
  z-index: 10;
  backdrop-filter: blur(10px);

  .user-avatar-area {
    display: flex;
    justify-content: center;
    position: relative;
    height: 150rpx;
    margin-bottom: 20rpx;

    .avatar {
      border: 6rpx solid rgba(255, 255, 255, 0.9);
      box-shadow: 0 8rpx 24rpx rgba(139, 92, 255, 0.25);
      border-radius: 50%;
      transition: transform 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
    }
  }

  .user-info {
    margin-top: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .username {
      font-size: 34rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 6rpx;
    }

    .gender-info {
      font-size: 26rpx;
      color: #8b5cff;
      background-color: rgba(139, 92, 255, 0.1);
      padding: 6rpx 20rpx;
      border-radius: 20rpx;
      margin-top: 10rpx;
    }
  }

  .edit-profile-btn {
    position: absolute;
    right: 30rpx;
    top: 30rpx;
    display: flex;
    align-items: center;
    background-color: rgba(139, 92, 255, 0.1);
    border-radius: 30rpx;
    padding: 12rpx 20rpx;

    text {
      font-size: 24rpx;
      color: #8b5cff;
      margin-left: 6rpx;
    }

    &:active {
      opacity: 0.8;
    }
  }
}

/* 设置板块 */
.settings-section {
  margin: 0 30rpx 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.03);

  .section-header {
    display: flex;
    align-items: center;
    padding: 20rpx;
    margin-bottom: 10rpx;

    .paw-mark {
      width: 36rpx;
      height: 36rpx;
      background-color: #ffd687;
      border-radius: 50%;
      margin-right: 16rpx;
      position: relative;

      &::before {
        content: "";
        position: absolute;
        top: -12rpx;
        left: -4rpx;
        width: 18rpx;
        height: 18rpx;
        background-color: #ffd687;
        border-radius: 50%;
      }

      &::after {
        content: "";
        position: absolute;
        top: -12rpx;
        right: -4rpx;
        width: 18rpx;
        height: 18rpx;
        background-color: #ffd687;
        border-radius: 50%;
      }
    }

    text {
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
    }
  }
}

/* 设置列表 */
.settings-list {
  .settings-item {
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1px solid #f0f0f0;
    justify-content: space-between;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background-color: #f9f9f9;
      border-radius: 12rpx;
    }

    .item-left {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .icon-wrapper {
        width: 48rpx;
        height: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .item-text {
        font-size: 28rpx;
        color: #333333;
      }
    }
  }
}

/* 退出登录按钮 */
.logout-container {
  padding: 30rpx;
  margin-top: 30rpx;

  .logout-button {
    background: linear-gradient(to right, #8b5cff, #a68cfe);
    color: white;
    border-radius: 40rpx;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 30rpx;
    box-shadow: 0 8rpx 16rpx rgba(139, 92, 255, 0.3);

    &:active {
      opacity: 0.9;
    }
  }
}

/* 底部装饰 */
.footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80rpx;
  overflow: hidden;

  .paw-steps {
    height: 80rpx;
    width: 100%;
    position: absolute;
    bottom: 0;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="40" viewBox="0 0 400 40"><g opacity="0.2" fill="%238B5CFF"><circle cx="8" cy="12" r="4"/><circle cx="2" cy="8" r="2"/><circle cx="14" cy="8" r="2"/><circle cx="4" cy="25" r="4"/><circle cx="25" cy="12" r="4"/><circle cx="19" cy="8" r="2"/><circle cx="31" cy="8" r="2"/><circle cx="21" cy="25" r="4"/><circle cx="42" cy="12" r="4"/><circle cx="36" cy="8" r="2"/><circle cx="48" cy="8" r="2"/><circle cx="38" cy="25" r="4"/><circle cx="59" cy="12" r="4"/><circle cx="53" cy="8" r="2"/><circle cx="65" cy="8" r="2"/><circle cx="55" cy="25" r="4"/><circle cx="76" cy="12" r="4"/><circle cx="70" cy="8" r="2"/><circle cx="82" cy="8" r="2"/><circle cx="72" cy="25" r="4"/><circle cx="93" cy="12" r="4"/><circle cx="87" cy="8" r="2"/><circle cx="99" cy="8" r="2"/><circle cx="89" cy="25" r="4"/></g></svg>');
    background-repeat: repeat-x;
    opacity: 0.5;
  }
}

/* 用户资料修改弹窗 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.update-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 600rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  z-index: 1000;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;

    .popup-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333333;
    }

    .close-btn {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .popup-content {
    .avatar-upload {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;
      position: relative;

      .current-avatar {
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;
        border: 3rpx solid #f0f0f0;
        background-color: #f5f5f5;
        object-fit: cover;
      }

      .upload-btn {
        position: absolute;
        right: 196rpx;
        bottom: 0;
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
        background: #8b5cff;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 3rpx solid #ffffff;
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);

        &:active {
          opacity: 0.8;
        }
      }
    }

    .form-item {
      margin-bottom: 30rpx;

      .form-label {
        font-size: 28rpx;
        color: #666666;
        margin-bottom: 16rpx;
        display: block;
      }

      .form-input {
        width: 100%;
        height: 90rpx;
        border: 1px solid #f0f0f0;
        border-radius: 45rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
        background-color: #f9f9f9;
      }
    }

    .gender-selector {
      display: flex;
      gap: 20rpx;

      .gender-option {
        flex: 1;
        height: 90rpx;
        border: 1px solid #f0f0f0;
        border-radius: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f9f9f9;

        &.selected {
          background: rgba(139, 92, 255, 0.1);
          border-color: #8b5cff;

          text {
            color: #8b5cff;
            font-weight: 500;
          }
        }

        text {
          font-size: 28rpx;
          color: #666;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }

    .submit-button {
      background: linear-gradient(to right, #8b5cff, #a68cfe);
      color: white;
      border-radius: 45rpx;
      height: 90rpx;
      line-height: 90rpx;
      font-size: 30rpx;
      box-shadow: 0 8rpx 16rpx rgba(139, 92, 255, 0.3);
      width: 100%;
      margin-top: 20rpx;
    }
  }
}
</style>